<template>
    <div class="table-box">
        <div class="card table-search">
            <el-form label-width="auto" :inline="true">
                <el-form class="search-form">
                    <!-- 经销商名称输入框 -->
                    <el-form-item label="经销商名称">
                        <el-input v-model="initParam.carrierName" placeholder="请输入经销商名称" style="width: 200px" />
                    </el-form-item>

                    <!-- 所属机构下拉框（假设数据从字典获取） -->
                    <el-form-item label="所属机构">
                        <!-- <el-select v-model="initParam.orgId" placeholder="请选择所属机构" style="width: 200px">
                            <el-option v-for="org in orgList" :key="org.value" :label="org.label" :value="org.value" />
                        </el-select> -->
                        <MySelect v-model="initParam.belong" :request-api="listDealerManage" placeholder="请选择所属机构"
                            :fieldNames="memberFiled" :data="initParam" :initParam="{ pageNum: 1, pageSize: 99999 }"
                            style="width: 200px" />
                    </el-form-item>

                    <!-- 所属状态下拉框 -->
                    <el-form-item label="所属状态">
                        <el-select v-model="initParam.status" placeholder="请选择状态" style="width: 200px">
                            <el-option label="启用" value="0" />
                            <el-option label="禁用" value="1" />
                        </el-select>
                    </el-form-item>

                    <!-- 查询/重置按钮 -->
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="getTableList">搜索</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-form>
        </div>

        <div class="card ">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="openDiolg('新增', null)">新增</el-button>
                </el-col>

            </el-row>
            <div class="operation-box">
                <!-- 修改循环数据源为mockList -->
                <div class="operation-item" v-for="(item, index) in mockList" :key="item.id">
                    <!-- 原有item内容保持不变 -->
                    <div class="item-main">
                        <div class="left-info">
                            <!-- <img :src="item.logo" alt="店铺logo" class="shop-logo" /> -->
                            <div class="text-info">
                                <p class="shop-name">{{ item.carrierName }}</p>
                                <p class="contact-info">{{ item.director }} | {{ item.phone }}</p>
                            </div>
                        </div>
                        <div class="right-actions">
                            <span class="status-tag" :class="item.status == '0' ? 'active' : 'inactive'">
                                {{ item.status == '0' ? '启用' : '禁用' }}
                            </span>
                            <el-button type="text" icon="EditPen" @click="openDiolg('编辑', item)">编辑</el-button>
                            <el-button type="text" icon="Delete" @click="deleteAccount(item)">删除</el-button>
                        </div>
                    </div>
                    <div class="auth-series">
                        <el-divider content-position="left">授权系列</el-divider>
                        <div class="series-tags">
                            <el-tag v-for="series in item.optionalSeries" :key="series" type="info">
                                {{ series }}
                            </el-tag>
                        </div>
                    </div>
                </div>
            </div>
            <pagination :total="totals" v-model:page="initParam.pageNum" v-model:limit="initParam.pageSize"
                @pagination="getTableList" />
        </div>

    </div>
</template>

<style scoped>
.operation-box {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    /* 项间距 */
    padding: 20px;
}

.operation-item {
    width: calc((100% - 40px) / 3);
    /* 一行3个，总间距40px（20px*2） */
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.item-main {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
}

.left-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.shop-logo {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border-radius: 4px;
}

.shop-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
}

.contact-info {
    font-size: 14px;
    color: #606266;
}

.right-actions {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;
}

.status-tag {
    font-size: 14px;
    padding: 2px 8px;
    border-radius: 12px;
}

.status-tag.active {
    background: #e6f4ea;
    color: #67c23a;
}

.status-tag.inactive {
    background: #fde2e2;
    color: #f56c6c;
}

.auth-series {
    margin-top: 12px;
}

.series-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
}
</style>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, getCurrentInstance, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, tabBarProps } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import {
    ColumnProps,
} from "@/components/ProTable/interface";
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
import {
    deviceNumList,
    devTypeList,
    devOnlineStatusList,
    devUseStatusList,
    findLabel,
} from "@/utils/stata";
import {
    listSupplier,
    getSupplier,
    delSupplier,
    addSupplier,
    updateSupplier
} from "@/api/zc/SupplierMagment";
import {
    listDealerManage,
} from "@/api/system/dealerManage";
import {
    listCarrier,
    getCarrier,
    delCarrier,
    addCarrier,
    updateCarrier
} from "@/api/zc/operation";
import { getDicts } from "@/api/system/dict/data";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { useHandleData } from "@/hooks/useHandleData";
import CryptoJS from 'crypto-js';
const proxy = getCurrentInstance()?.proxy;
const emit = defineEmits(["changeItem"]);
const { sys_user_sex } = toRefs<any>(proxy?.useDict("sys_user_sex"));
const publicKey = import.meta.env.VITE_APP_PUBLICKEY; //引入公钥
const router = useRouter();
const ExcelRef = ref(null);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<any>();
let memberFiled = { label: "dealerName", value: "id", labelName: "dealerName", autoLable: false };
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
    carrierName: '',  // 经销商名称
    belong: '',       // 所属机构ID
    status: '',       // 所属状态（0/1）
    pageNum: 1,
    pageSize: 9,
});
const totals = ref(0);
const resetQuery = () => {
    initParam.carrierName = '';
    initParam.belong = '';
    initParam.status = '';
    getTableList();
}
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
    return { list: data.rows, total: data.total };
};


// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = async () => {
    let { rows, total } = await listCarrier(initParam);
    mockList.value = rows.map((item: any) => {
        return {
            ...item,
            optionalSeries: item.optionalSeries.split(','),
        };
    });
    totals.value = total;
    // return listSupplier(params);
};
getTableList();
const templateParams = {
    templateName: "demo模板",
    templateUrl: "system/user/importTemplate",
    templateType: 0,
    templateObj: {}
}


const changeStatus = async (row: any, key: string) => {
    // await useHandleData(updateSign, { ...row, key: row[key] == 1 ? 0 : 1 }, `切换状态`);
    await updateSupplier({ ...row, key: row[key] == 1 ? 0 : 1 });
    ElMessage.success({ message: `调整合作状态成功！` });
    proTable.value?.getTableList();
};
// 删除用户信息
const deleteAccount = async (params: any) => {
    const ids = params.id
    await useHandleData(delCarrier, ids, '是否删除编号为' + ids + '的数据');
    getTableList();
};
//模拟 调用接口
const PromiseDel = () => new Promise((resolve, reject) => resolve(true))

/** 导出按钮操作 */
function handleExport() {
    proxy.download("system/user/export", {

    }, `user_${new Date().getTime()}.xlsx`);
};

const openDiolg = async (title: string, rowData: any) => {
    let params: any = {
        title,
        isView: title === "查看",
        rowData: { ...rowData },
        api: title === "新增" ? addCarrier : title === "编辑" ? updateCarrier : undefined,
        getTableList: proTable.value?.getTableList,
    };
    if (title === "新增") {
        params.rowData.selectedSeries = []
        
    } else {
        let { data } = await getCarrier(rowData.id)
        params.rowData = data;
        // params.rowData.availableSeries =[];
        // params.rowData.password = CryptoJS.AES.decrypt(params.rowData.password, publicKey).toString(CryptoJS.enc.Utf8), { expires: 30 }
        params.rowData.selectedSeries = params.rowData.optionalSeries.split(',')
        console.log(params.rowData)
    }
    emit("changeItem", "1", params, title);
};

// 新增模拟数据（包含图片地址、店名、联系方式等）
const mockList = ref([
    // {
    //     id: 1,
    //     logo: 'https://via.placeholder.com/50x50?text=杭州旗舰店', // 占位图服务
    //     shopName: '杭州旗舰店',
    //     contactName: '张经理',
    //     phone: '138-1234-5678',
    //     status: '1', // 1=启用
    //     authSeries: ['奢华印象', '经典系列']
    // },
    // {
    //     id: 2,
    //     logo: 'https://via.placeholder.com/50x50?text=上海体验店',
    //     shopName: '上海体验店',
    //     contactName: '李总监',
    //     phone: '139-8765-4321',
    //     status: '0', // 0=禁用
    //     authSeries: ['普通质感', '现代简约']
    // },
    // {
    //     id: 3,
    //     logo: 'https://via.placeholder.com/50x50?text=广州形象店',
    //     shopName: '广州形象店',
    //     contactName: '王店长',
    //     phone: '186-0000-1111',
    //     status: '1',
    //     authSeries: ['高端定制', '轻奢风尚']
    // },
    // 可根据需要添加更多模拟数据
]);


onMounted(() => {
    setTimeout(() => {
        const { add, ...query } = router.currentRoute.value.query;
        if (add == 0) {
            openDiolg('新增', null)

            // 成功后移除add参数
            router.replace({ query });
        }
    }, 1000)
})
</script>
